import { createRouter, createWebHashHistory } from 'vue-router'
import { ElMessage } from 'element-plus' //引入element-plus的消息提示组件
import Login from '@/components/Login.vue'  //引入login页面组件
import Home from '@/components/Home.vue'   //引入home页面组件
import User from '@/views/user.vue'     
import Modify from '@/views/modify.vue'    
import Sport from '@/views/sport.vue'     
import Goods from '@/views/goods.vue'     
import Introduction from '@/views/introduction.vue'
import Calories from '@/views/calories.vue'
import Food from '@/views/food.vue'
import indexHome from '@/views/indexHome.vue'


const routes = [
  {
    path:"/",
    redirect:"/login" //默认重定向到登录页面
  },
  {
    path:"/login",
    name:"login",
    component:Login
  },
  {
    path:"/home",
    name:"home",
    component:Home,
    children: [
        {
        path:"",
        redirect:"/home/indexHome" //默认重定向到的页面
      },
      {
        path:"indexHome",
        name:"indexHome",
        component:indexHome
      },
      {
        path:"user",
        name:"user",
        component:User
      },
      {
        path:"modify",
        name:"modify",
        component:Modify
      },
      {
        path:"sport",
        name:"sport",
        component:Sport
      },
      {
        path:"goods",
        name:"goods",
        component:Goods
      },
      {
        path:"introduction",
        name:"introduction",
        component:Introduction
      },
      {
        path:"calories",
        name:"calories",
        component:Calories
      },
      {
        path:"food",
        name:"food",
        component:Food
      }
    ]
  }
]

//创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //to 将要访问
  //from 代表从哪个页面来
  //next() 放行,接着访问
  if(to.path=="/login"){
    return next() //如果访问的是登录页面，直接放行
  }

  //判断是否有token
  const userToken=localStorage.getItem("userToken")  //获取token
  if(userToken){
    return next() //如果有token，直接放行
  }else{
   //如果没有token，且访问的不是登录页面，跳转到登录页面
   ElMessage.error("请先登录!")
   next("/login")
  }

})

export default router
